package top.catchcat.blogs.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import top.catchcat.blogs.dao.AccessTokenDAO;
import top.catchcat.blogs.dao.userIfo.GiteeUser;
import top.catchcat.blogs.dao.userIfo.GithubUser;
import top.catchcat.blogs.dao.userIfo.User;
import top.catchcat.blogs.service.impl.LoginServiceImpl;
import top.catchcat.blogs.utils.GiteeProvider;
import top.catchcat.blogs.utils.GithubProvider;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

@Controller
public class AuthorizeController {
//    https://gitee.com/oauth/authorize?client_id=9ec64a0854dccc034e8a9ec8fd1cfcf5bf7f8a0e7ce605db907414e917f19762&redirect_uri=http://localhost:8080/giteeCallback&response_type=code

    @Autowired
    private GithubProvider githubProvider;

    @Autowired
    private GiteeProvider giteeProvider;

    @Autowired
    private LoginServiceImpl indexService;

    @Value("${github.client.id}")
    private String githubClientId;

    @Value("${github.client.secret}")
    private String githubClientSecret;

    @Value("${github.redirect.uri}")
    private String githubRedirectUri;

    @Value("${gitee.client.id}")
    private String giteeClientId;

    @Value("${gitee.client.secret}")
    private String giteeClientSecret;

    @Value("${gitee.redirect.uri}")
    private String giteeRedirectUri;

    private AccessTokenDAO accessTokenDAO = new AccessTokenDAO();

    @GetMapping("/githubCallback")
    public String githubCallback(@RequestParam(name = "code") String code,
                                 @RequestParam(name = "state") String state,
                                 HttpServletResponse response,
                                 RedirectAttributes attributes){
        accessTokenDAO.setClient_id(githubClientId);
        accessTokenDAO.setClient_secret(githubClientSecret);
        accessTokenDAO.setRedirect_uri(githubRedirectUri);
        accessTokenDAO.setCode(code);
        accessTokenDAO.setState(state);
        String accessToken = githubProvider.getAccessToken(accessTokenDAO);
        GithubUser githubUser = githubProvider.getUser(accessToken);
        System.out.println(githubUser+",github");
        if (githubUser !=null && githubUser.getId() != null){
            User user = new User();
            user.setAccount_id(githubUser.getId());
            user.setName(githubUser.getName());
            user.setAvatar_url(githubUser.getAvatar_url());
            String token = UUID.randomUUID().toString();
            user.setToken(token);
            Cookie cookie = new Cookie("token", token);
            cookie.setMaxAge(60*60*24);
            response.addCookie(cookie);
            indexService.githubLogin(user);
        }else {
            attributes.addFlashAttribute("msg","登录失败，稍后请重新再试");
        }
        return "redirect:/";
    }
    @GetMapping("/giteeCallback")
    public String giteeCallback(@RequestParam("code") String code,
                                @RequestParam("state") String state,
                                HttpServletResponse response,
                                RedirectAttributes attributes) {
        accessTokenDAO.setClient_id(giteeClientId);
        accessTokenDAO.setClient_secret(giteeClientSecret);
        accessTokenDAO.setRedirect_uri(giteeRedirectUri);
        accessTokenDAO.setCode(code);
        accessTokenDAO.setState(state);
        String accessToken = giteeProvider.getAccessToken(accessTokenDAO);
        GiteeUser giteeUser = giteeProvider.getGiteeUser(accessToken);
        System.out.println(giteeUser+",gitee");
        if (giteeUser != null && giteeUser.getId() != null) {
            User user = new User();
            String token = UUID.randomUUID().toString();
            user.setAccount_id(giteeUser.getId());
            user.setName(giteeUser.getName());
            user.setAvatar_url(giteeUser.getAvatarUrl());
            user.setToken(token);
            Cookie cookie = new Cookie("token", token);
            cookie.setMaxAge(60*60*24);
            response.addCookie(cookie);
            indexService.githubLogin(user);
        }else {
            attributes.addFlashAttribute("msg","登录失败，稍后请重新再试");
        }
        return "redirect:/";
    }

    @GetMapping("/logout")
    public String logout(HttpServletRequest request,
                         HttpServletResponse response) {
        request.getSession().removeAttribute("user");
        Cookie cookie = new Cookie("token", null);
        cookie.setMaxAge(0);
        response.addCookie(cookie);
        return "redirect:/";
    }
}
